/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.unicode.unihan.parser;

import org.geergenbein.parser.ParserException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.geergenbein.parser.LineParser;
import org.unicode.unihan.domain.UnihanRow;

/**
 *
 * @author Andrew
 */
public class UnihanLineParser implements LineParser<UnihanRow> {

    private final static String UNICODE_PREFIX = "U+";
    private final static String KEY_PREFIX ="k";
    private final static String FIELD_SEPARATOR = "\t";

    // TODO: find a generic package that can escape special regex characters
    private final static Pattern LINE_REGEX =
            Pattern.compile("^" + UNICODE_PREFIX.replace("+", "\\+") +
            "([\\dA-Fa-f]{4,5})" + FIELD_SEPARATOR + KEY_PREFIX +
            "([A-Z]\\w+)" + FIELD_SEPARATOR + "(.*)");
    private final static int RADIX = 16;

    public UnihanRow parse(String line) {
        UnihanRow unihanRow = null;
        Matcher m = LINE_REGEX.matcher(line);
        if (m.find()) {
            String unicodeString = m.group(1);
            int unicode = Integer.parseInt(unicodeString, RADIX);
            String key = m.group(2);
            String value = m.group(3);
            unihanRow = new UnihanRow(unicode, key, value);
        } else {
            throw new ParserException("Failed to parse line '" + line + "' " +
                    "with regex '" + LINE_REGEX.toString() + "'");
        }
        return unihanRow;
    }

    // TODO: add a toString function that takes three parameters so you don't
    // have to create UnihanRow object
    public String toString(UnihanRow unihanRow) {
        return UNICODE_PREFIX + Integer.toHexString(unihanRow.getUnicode()).
                toUpperCase() + FIELD_SEPARATOR + KEY_PREFIX +
                unihanRow.getKey() + FIELD_SEPARATOR + unihanRow.getValue();
    }
    
}
